package com.countertack.testcases;

import java.net.InetAddress;
import java.sql.ResultSet;

import org.doublecloud.vi.vmware.guest.GuestProcessDirector;

import com.countertack.impala.ImpalaConnector;
import com.countertack.utils.Configuration;
import com.countertack.utils.HttpClientUtils;
import com.countertack.utils.Utils;
import com.countertack.vmware.VMWareConnector;
import com.countertack.vmware.VMWareUtils;
import com.vmware.vim25.mo.VirtualMachine;

public class ProcessExclusion_Example_1 {

	public static void main(String[] args) throws Exception {
		StringBuffer testCaseResult = new StringBuffer();
		ImpalaConnector iConnector = null;
		VMWareConnector esxiConnector = null;

		try {
			
			 if (args.length <= 0) {
			 
			 System.out.println("configuration details missed !");
			 testCaseResult.append("configuration details missed ! \n");
			 return; } String configFilePath = args[0];
			 

			//String configFilePath = "C:\\Users\\user\\Desktop\\smoketestautomation\\config.properties";

			Configuration.loadProperties(configFilePath);

			String vmUser = Configuration.getProperty("vmuser");
			String vmPassword = Configuration.getProperty("vmpassword");

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(Configuration
					.getProperty("sentinelehost"));

			InetAddress address = InetAddress.getByName(Configuration
					.getProperty("sentinelehost"));
			String sentenelIp = address.getHostAddress();
			System.out.println(address.getHostAddress());
			// connect to esxi and starting virtual machines

			esxiConnector = new VMWareConnector(
					Configuration.getProperty("esxi"));
			// poweredOn
			VirtualMachine endPointMachine = esxiConnector
					.getVirtualMachineByname(Configuration
							.getProperty("vmname"));
			testCaseResult.append("VMName>>>>"
					+ Configuration.getProperty("vmname") + "\n");

			// win7x64-sym-2
			System.out.println("power state >>>"
					+ endPointMachine.getRuntime().powerState);

			String endpointMachineStatus = null;

			// System.out.println("VM Ip Address>>>" + vmIp);
			String smokeSnapShotName = Configuration
					.getProperty("rootsnapshotname");
			esxiConnector.revertToSnapShort(endPointMachine.getSnapshot()
					.getRootSnapshotList(), smokeSnapShotName);

			System.out.println("Reverting to root snap shot>>>>>"
					+ smokeSnapShotName);

			esxiConnector.checkAndRunVirtualMachine(endPointMachine);

			String vmIp = Configuration.getProperty("vmip");
			if (vmIp == null || vmIp.trim() == "") {

				vmIp = endPointMachine.getGuest().ipAddress;
			}
			System.out.println("ip>>>" + endPointMachine.getGuest().ipAddress);
			testCaseResult.append("VM IP>>>>>>" + vmIp + "\n");
			testCaseResult.append("ESXI>>>>>"
					+ Configuration.getProperty("esxi") + "\n");

			boolean isXp = false;

			String osType = VMWareUtils.getVMOSArchitecture(
					Configuration.getProperty("esxi"),
					Configuration.getProperty("vmname"));
			if (osType != null) {

				osType = osType.toLowerCase();

				if (osType.contains("xp")) {

					isXp = true;
				}

			}

			GuestProcessDirector progDir = new GuestProcessDirector(
					endPointMachine, vmUser, vmPassword);

			// copying ipconfig.exe to Users/user folder

			if (isXp) {
				/*progDir.run("C:\\Windows\\System32\\cmd.exe",
						"/c copy C:\\Windows\\System32\\ipconfig.exe \"C:\\Documents and Settings\\"
								+ vmUser + "\\ipconfig.exe\"");*/
				progDir.run("C:\\Windows\\System32\\cmd.exe",
						"/c copy C:\\Windows\\System32\\cmd.exe \"C:\\Documents and Settings\\"
								+ vmUser + "\\cmd.exe\"");

			} else {
			/*	progDir.run("C:\\Windows\\System32\\cmd.exe",
						"/c copy C:\\Windows\\System32\\ipconfig.exe C:\\Users\\"
								+ vmUser + "\\ipconfig.exe");*/

				progDir.run("C:\\Windows\\System32\\cmd.exe",
						"/c copy C:\\Windows\\System32\\cmd.exe C:\\Users\\"
								+ vmUser + "\\cmd.exe");

			}
			// Documents and Settings
			Thread.sleep(60000);

			String eId = VMWareUtils
					.installKM(Configuration.getProperty("esxi"), null,
							Configuration.getProperty("vmname"), sentenelIp,
							vmIp, vmUser, vmPassword,
							Configuration.getProperty("driverpath"));

			if (eId == null) {

				System.out.println("Unable to install KM");
				testCaseResult.append("Unable to install KM" + "\n");
				return;
			}

			Utils.pauseEndpoint(eId);

			Thread.sleep(60000);

			String payload = "{ "
					+ "  \"type\": \"apply_profile_to_endpoints\", "
					+ "  \"profile\":\""
					+ Configuration.getProperty("profilename") + "\", "
					+ "  \"endpoints\":[ " + "\"" + eId + "\" " + "] " + "} ";

			HttpClientUtils.composePostRequest(
					Configuration.getProperty("restapirooturi")
							+ "/endpoints/command", payload);

			Thread.sleep(3000);

			Utils.resumeEndpoint(eId);

			Thread.sleep(60000);

			if (isXp) {

				/*progDir.run(
						"C:\\Documents and Settings\\" + vmUser + "\\cmd.exe",
						"/c echo \"cmd.exe created file\" > \"c:\\Documents and Settings\\"
								+ vmUser
								+ "\\processexclusionexample1cmd_created.txt\" && \"c:\\Documents and Settings\\"
								+ vmUser
								+ "\\ipconfig.exe\""
								+ " > \"c:\\Documents and Settings\\"
								+ vmUser
								+ "\\processexclusionexample1ipconfig_created.txt\"");*/
				
				
				
				
				progDir.run(
						"C:\\Documents and Settings\\" + vmUser + "\\cmd.exe",
						"/c echo \"cmd.exe created file\" > \"c:\\Documents and Settings\\"
								+ vmUser
								+ "\\processexclusionexample1cmd_created.txt\" && ipconfig > \"c:\\Documents and Settings\\"
								+ vmUser
								+ "\\processexclusionexample1ipconfig_created.txt\"");

			} else {

			/*	progDir.run(
						"C:\\Users\\" + vmUser + "\\cmd.exe",
						"/c echo \"cmd_exe createdfile\" > c:\\Users"
								+ vmUser
								+ "\\processexclusionexample1cmd_created.txt && c:\\Users\\"
								+ vmUser
								+ "\\ipconfig.exe > c:\\Users\\"
								+ vmUser
								+ "\\processexclusionexample1ipconfig_created.txt");*/
				
				
				
				progDir.run(
						"C:\\Users\\" + vmUser + "\\cmd.exe",
						"/c echo \"cmd_exe createdfile\" > c:\\Users"
								+ vmUser
								+ "\\processexclusionexample1cmd_created.txt && ipconfig.exe > c:\\Users\\"
								+ vmUser
								+ "\\processexclusionexample1ipconfig_created.txt");
			}

			Thread.sleep(60000);

			// 7055

			// verifying cmd.exe process exclusion

			String bhid = null;

			String bhidQuery = "select hex(behaviors.id)  from behaviors INNER JOIN  behaviors_denorm on behaviors.id=behaviors_denorm.behavior_id where behaviors.uri like '%"
					+ eId
					+ "%' and behaviors_denorm.target_process_name like '%cmd.exe%' and behaviors_denorm.behavior_id is not null and behaviors_denorm.target_process_name is not null order by behaviors.event_start_time desc limit 1";
			// verifying process
			ResultSet bhidRes = iConnector
					.executeQueryAndReturnResults(bhidQuery);

			while (bhidRes.next()) {

				bhid = bhidRes.getString(1);

			}

			if (bhid == null) {

				System.out
						.println("Verifying process exclusion(cmd.exe)------------>Pass");
				testCaseResult
						.append("Verifying process exclusion(cmd.exe)------------>Pass \n");

			}

			else {

				System.out
						.println("Verifying process exclusion(cmd.exe)------------>Fail");
				testCaseResult
						.append("Verifying process exclusion(cmd.exe)------------>Fail \n");
				testCaseResult.append("Behavior id>>>>>" + bhid + "\n");
			}

			// verifying ipconfig.exe started by cmd.exe
			bhid = null;
			bhidQuery = "select hex(behaviors.id)  from behaviors INNER JOIN  behaviors_denorm on behaviors.id=behaviors_denorm.behavior_id where behaviors.uri like '%"
					+ eId
					+ "%' and behaviors_denorm.target_process_name like '%ipconfig.exe%' and behaviors_denorm.behavior_id is not null and behaviors_denorm.target_process_name is not null order by behaviors.event_start_time desc limit 1";
			// verifying process
			bhidRes = iConnector.executeQueryAndReturnResults(bhidQuery);

			while (bhidRes.next()) {

				bhid = bhidRes.getString(1);

			}

			if (bhid == null) {

				System.out
						.println("Verifying process exclusion(ipconfig.exe started by cmd.exe)------------>Pass");
				testCaseResult
						.append("Verifying process exclusion(ipconfig.exe started by cmd.exe)------------>Pass \n");

			}

			else {

				System.out
						.println("Verifying process exclusion(ipconfig.exe started by cmd.exe)------------>Fail");
				testCaseResult
						.append("Verifying process exclusion(ipconfig.exe started by cmd.exe)------------>Fail \n");
				testCaseResult.append("Behavior id>>>>>" + bhid + "\n");
			}

		} finally {

			try {
				if (esxiConnector != null) {

					esxiConnector.closeEsxiConnection();
				}
			} catch (Exception e) {

				e.printStackTrace();
			}

			try {
				if (iConnector != null) {
					iConnector.closeImpalaConnection();

				}
			} catch (Exception e) {
				e.printStackTrace();

			}
			Utils.addResultsToLog(testCaseResult,
					"verifying_process_exclusion_example1",
					Configuration.getProperty("vmname"));

		}

	}

}
